package com.rpc.demo.provider.handler;

import com.rpc.demo.common.model.Invocation;
import com.rpc.demo.common.util.ApplicationContextGetBeanHelper;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

/**
 * @Author: ZhaoJie
 * @Date: 2022/4/7
 * @Description:
 * @Modify: ===================================================
 * Modifier        Modifytime        Description
 * ===================================================
 */
@ChannelHandler.Sharable
public class ProviderNettyHandler extends ChannelInboundHandlerAdapter {

    //与服务器的连接创建后，就会被调用, 这个方法是第一个被调用(1)
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(" channelActive 被调用  ");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object message) throws Exception {
        // 通过class name来获取实例对象
        Invocation invocation = (Invocation) message;
        //执行对应方法
        String[] classPath = invocation.getInterfaceName().split("\\.");
        String classBeanName = classPath[classPath.length - 1];
        // 通过传过来的class 名字从beanfactory中获取对应的实例
        Class class1 = ApplicationContextGetBeanHelper.getBean(classBeanName);
        // 反射拿到方法
        Method method = class1.getMethod(invocation.getMethodName(), invocation.getParamTypes());
        // 反射得到结果
        Object result = method.invoke(class1.newInstance(), invocation.getParams());
        // 返回方法执行结果
        ctx.writeAndFlush(result);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
